function post_to_url(path, params, method) {
		method = method || "post"; // Set method to post by default, if not specified.
		var form = document.createElement("form");
		form.setAttribute("method", method);
		form.setAttribute("action", path);
		form.setAttribute("enctype", "multipart/form-data")
		for (var key in params) {
			var hiddenField = document.createElement("input");
			hiddenField.setAttribute("type", "hidden");
			hiddenField.setAttribute("name", key);
			hiddenField.setAttribute("value", params[key]);
			form.appendChild(hiddenField);
		}
		document.body.appendChild(form);    // Not entirely sure if this is necessary
		form.submit();
	}
function sleep(milliSeconds){
var startTime = new Date().getTime(); // get the current time
while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}
function tb_hover() {
	$(".on").hover(
			function () {
				$(this).children(".outer").hide();
			},
			function () {
				$(this).children(".outer").show();
			}
	);
}
function activate_fields() {
	var f = $('#childs form');
	$("#childs").html($('#childs table'));
	$("#childs").append(f);
	$("#childs td.id").each(function(i, val) {
		$("#child_text").append($(this).html())
	});
	$("textarea.field_description").jGrow({ rows: 2500 });
	$("textarea#comment").jGrow({ rows: 2500 });
	$("textarea#field-summary").jGrow({ rows: 2500 });
	$("#cont div.show_hide").hide();
	$("#edit_form").show();
	$('#cont div.edit_tab').eq(0).addClass('active');
	$("#cont div.edit_tab.tab_hover").click(function () {
		$('#cont div.edit_tab.tab_hover').removeClass('active');
		$(this).addClass('active');
		if ($('#cont div.edit_tab.tab_hover').eq(0).hasClass('active')) {
			$("#cont div.show_hide").hide();
			$("#edit_form").show();
		}
		if ($('#cont div.edit_tab.tab_hover').eq(1).hasClass('active')) {
			$("#cont div.show_hide").hide();
			$("#childs_out").show();
		}
		if ($('#cont div.edit_tab.tab_hover').eq(2).hasClass('active')) {
			$("#cont div.show_hide").hide();
			$("#history_out").show();
		}
	});
	$("#update_attach").click(function() {
		//alert()
		var s = location.pathname.split('/')
		//alert(location.pathname)
		//alert(s[s.length-1])
		//alert(s[s.length-3])
		var database = s[s.length - 3]
		var ticket_id = s[s.length - 1]
		post_to_url("/supervisor/ticket_sync", {'database': database, 'ticket_id': ticket_id})
	});
	function post_to_url(path, params, method) {
		method = method || "post"; // Set method to post by default, if not specified.
		var form = document.createElement("form");
		form.setAttribute("method", method);
		form.setAttribute("action", path);
		form.setAttribute("enctype", "multipart/form-data")
		for (var key in params) {
			var hiddenField = document.createElement("input");
			hiddenField.setAttribute("type", "hidden");
			hiddenField.setAttribute("name", key);
			hiddenField.setAttribute("value", params[key]);
			form.appendChild(hiddenField);
		}
		document.body.appendChild(form);    // Not entirely sure if this is necessary
		form.submit();
	}

	//-------------------------------------------------------------------
	$("#edit_properties select").change(function () {
		var str = this.text
		if (this.selectedIndex != -1)
			var str = this[this.selectedIndex].text;
		$(this).prevAll('.outer:first').html("<span>" + str + "</span>");
		tb_hover();
	})
			.change();
	$("#edit_properties input").change(function () {
		var cur = this
		var str = $(this).val();
		if (cur.parentNode.tagName == 'SPAN') cur = cur.parentNode
		$(cur).prevAll('.outer:first').html("<span>" + str + "</span>");
		tb_hover();
	})
			.change();
	$("#out-parent.outer").before("<div id='parent'>#158888</div>");
	$("#field-parent").change(function () {
		var str = $(this).val();
		str1 = str.replace('#', "");
		$(this).prevAll('#parent').html("<span><a href='" + str1 + "'>" + str + "</a></span>");
	})
			.change();
	$('#parent').click(function() {
		$(this).hide();
		$("#field-parent").focus();
	});
	$("#field-summary").change(function () {
		var str = $(this).val();
		if (str == false) {
			str = "<span class='gray'>--заголовок--</span>";
		}
		$('.two pre').html("<pre>" + str + "</pre>");
		var height = $('#field-summary').height();
		height = parseInt(height);
		height = height + 'px';
		$(".two").css('height', height);
	})
			.change();
	var k = '';
	$("textarea.field_description").change(function () {
		k = 'ok';
	})
	$("textarea.field_description").blur(function () {
		if (k == 'ok') {
			var str = $("textarea.field_description").val();
			if (str == false) {
				str = "<span class='gray'>--описание--</span>";
			}
			$('.two_ta .pre').html("<pre>" + str + "</pre>");
		}
	});
	if ($("textarea.field_description").val() == '') {
		str = "<span class='gray'>--описание--</span>";
		$('.two_ta .pre').html("<pre>" + str + "</pre>");
	}
	$('.two_ta .pre').click(function() {
		$('.two_ta').hide();
		$("#field-summary").show();
		$("textarea.field_description").focus();
	});
	$('.two pre').click(function() {
		$('.two').hide();
		$("#field-summary").focus();
	});
	$("#field-summary").focus(function () {
		$('.two').hide();
	});
	$("textarea.field_description").focus(function () {
		$('.two_ta').hide();
	});
	$('.two_ta .pre a').click(function() {
		window.location = this.href
		return false;
	});
	$(".two_ta .pre").hover(
			function () {
				$(this).parent(".two_ta").css({'border':'1px solid #e0e0e0','top':'-1px','left':'-1px'});
			},
			function () {
				$(this).parent(".two_ta").css({'border':'0 none','top':'0px','left':'0px'});
			}
	);
	$(".two pre").hover(
			function () {
				$(this).parent(".two").css('border', '1px solid #e0e0e0');
			},
			function () {
				$(this).parent(".two").css('border', '1px solid #fff');
			}
	);
	$(".on").hover(
			function () {
				$(this).children(".outer").hide();
			},
			function () {
				$(this).children(".outer").show();
			}
	);
	$("#edit_properties select, #edit_properties input").focus(function () {
		$(this).prevAll('.outer:first').addClass('none');
		$("#save_button").addClass('act');
	});
	$("#edit_properties select, #edit_properties input").blur(function () {
		$(this).prevAll('.outer:first').removeClass('none');
		$('#parent').show();
	});
	$("#edit_all_table select, #edit_all_table input, #edit_all_table textarea").focus(function () {
		$("#save_button").addClass('act');
	});
	$(".action_div").each(function() {
		if ($(this).find("input:radio").attr("checked")) {
			$(this).addClass("active");
		}
		;
	});
	$(".action_div").click(function() {
		$("#save_button").addClass('act');
		$(".action_div").removeClass("active");
		$(this).addClass("active");
		$(this).find("input:radio").attr("checked", "checked");
	});
	var ll = $("#out-mstask span").text();
	if (ll = 'null') {
		$("#out-mstask span").text('');
	}
}
function create_entity_func(title, entity_id) {
	var admin_parent_entity = $("#admin_parent_entity")
	if (admin_parent_entity.length != 0)
		parent_entity_value_id = admin_parent_entity[0][admin_parent_entity[0].selectedIndex].value;
//	$.get("/request_entity_content/" + entity_id + "/create", function(data) {
//		$("#create_entity").html(data)
//
//		$.get("/request_entity_properties/" + entity_id, function(data) {
//			$("#entity_properties").html(data)
//			activate_fields()
//			$(".datepick").datetimepicker({ dateFormat: 'dd/mm/yy', timeFormat: 'hh:mm' })
//			$("#create_entity").dialog({modal:true, autoOpen: false, width:1000,open:
//					function(event, ui) {
//					}});
//			$("#create_entity").dialog("option", "title", title);
//			$("#create_entity").dialog("open");
//		})
//	})
//	$.get("/entity/" + parent_entity_value_id + "/create" + entity_id)
	setCookie('lastCommand', '')
	
/*
	if (parent_entity_value_id == undefined)
		parent_entity_value_id = 0
	var admin_parent_entity = $("#admin_parent_entity")
	if (admin_parent_entity.length != 0)
		parent_entity_value_id = admin_parent_entity[0][admin_parent_entity[0].selectedIndex].value;
	$.get("/request_entity_content/" + entity_id + "/" + parent_entity_value_id + "/create", function(data) {
		$("#create_entity").html(data)

		//$.get("/request_entity_properties/" + entity_id + "/" + parent_entity_value_id + "/create", function(data) {
		$.get("/entity/" + entity_id + "/entity/" + parent_entity_value_id + "/properties", function(data) {
			$("#entity_properties").html(data)
			activate_fields()
			$(".datepick").datepicker({ dateFormat: 'dd/mm/yy' })
			$("#create_entity").dialog({modal:true, autoOpen: false, width:1000,open:
					function(event, ui) {
					}});
			$("#create_entity").dialog("option", "title", title);
			$("#create_entity").dialog("open");
		})
	})
	setCookie('lastCommand', '')
*/
}
function view_for_update_entity_func(title, entity_id, entity_value_id) {
	if (entity_value_id == undefined)
		entity_value_id = 0
	$.get("/request_entity_admin_view_for_update/" + entity_value_id + "/", function(data) {
		$("#entity_list").html(data)

		//activate_fields()
		$(".datepick").datetimepicker({ dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm' })
	})

	$.get("/entity/request_entity_properties/" + entity_id + "/", function(data) {
//	$.get("/entity/" + entity_id + "/entity/" + entity_value_id + "(\d*)/properties", function(data) {
/*
	$.get("/request_entity_properties/" + entity_id + "/" + entity_value_id + "/view", function(data) {*/
		$("#entity_properties_inline").html(data)
//		activate_fields()
		$(".datepick").datetimepicker({ dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm' })
	})


	$("#buttons_inline").hide()
	$("#admin_parent_entity").hide()
	//setCookie('lastCommand', '')

}
function draw_menu() {
	var url = location.href;
	$("#submenu").hide()

	if (url == "http://td/trac") {
		$('.main-menu li:eq(0)').addClass("active");
	}
	if (url == "http://127.0.0.1:8000/create_entity") {
		$('.main-menu li:eq(5)').addClass("active");
		$("#submenu").hide();
	}
	if (url == "http://127.0.0.1:8000/") {
		$('.main-menu li:eq(5)').addClass("active");
		$("#submenu").hide();
		$("#submenu1_ul li:eq(5)").addClass("active");
	}
	if (url == "http://127.0.0.1:8000/") {
		$('.main-menu li:eq(5)').addClass("active");
		$("#submenu").hide();
		$("#submenu1_ul li:eq(6)").addClass("active");
	}

	if (url == "http://td/supervisor/delivery/") {
		$('.main-menu li:eq(1)').addClass("active");
		$("#submenu").hide();
	}
	if (url == "http://td/supervisor") {
		$('.main-menu li:eq(2)').addClass("active");
		$('#submenu_ul li:eq(0)').addClass("active");
	}
	if (url == "http://td/supervisor/ticket") {
		$('.main-menu li:eq(2)').addClass("active");
		$('#submenu_ul li:eq(1)').addClass("active");
	}
	if (url == "http://td/supervisor/ticket_project") {
		$('.main-menu li:eq(2)').addClass("active");
		$('#submenu_ul li:eq(1)').addClass("active");
	}
	if (url == "http://td/supervisor/ticket_loss") {
		$('.main-menu li:eq(2)').addClass("active");
		$('#submenu_ul li:eq(1)').addClass("active");
	}


	if (url == "http://td/supervisor/support") {
		$('.main-menu li:eq(2)').addClass("active");
		$('#submenu_ul li:eq(2)').addClass("active");
	}
	if (url == "http://td/supervisor/kpi") {
		$('.main-menu li:eq(2)').addClass("active");
		$('#submenu_ul li:eq(3)').addClass("active");
	}
	if (url == "http://td/supervisor/support_ccbo") {
		$('.main-menu li:eq(2)').addClass("active");
		$('#submenu_ul li:eq(2)').addClass("active");
	}

	if (url == "http://td/supervisor/test") {
		$('.main-menu li:eq(2)').addClass("active");
		$('#submenu_ul li:eq(4)').addClass("active");
	}
}

function get_cont(entity_id, entity_value_id,page) {

	$.get("/entity/request_entity_value_table/" + entity_id + "/" + entity_value_id +"/"+page + "/", function(data) {
		$("#entity_list_" + entity_id).html(data)
	})
    }

function get_admin_table_func(entity_id, entity_value_id, selected_index) {
	var admin_parent_entity = $("#admin_parent_entity")
	if (admin_parent_entity.length != 0)
	{
		if (selected_index != undefined)
			admin_parent_entity[0].selectedIndex = selected_index
		entity_value_id = admin_parent_entity[0][admin_parent_entity[0].selectedIndex].value;
		setCookie('lastUrl', location.href)
		setCookie('lastSubCommandParam', [entity_id, entity_value_id, admin_parent_entity[0].selectedIndex])
		setCookie('lastSubCommand', 'get_admin_table_func')
	}



	$.get("/entity/request_entity_value_table/" + entity_id + "/" + entity_value_id + "/", function(data) {
		$("#entity_list").html(data)
	})
	//setCookie('lastSubCommandParam', [entity_id, entity_value_id])
}
function get_admin_func(section, entity_id, entity_value_id, self) {
	if (entity_id == undefined)
	{
		var param = section.split(',')
		section = param[0]
		entity_id = param[1]
		entity_value_id = param[2]
	}
	else
		setCookie('lastSubCommand', '')

	if (section == 'perm') {
	}
	if (section == 'logging') {
	}
	if (section == 'basic') {
	}
	if (section == 'entity') {
		$.get("/request_entity_admin/" + entity_id + "/" + entity_value_id + "/", function(data) {
			var s = "a#entity_"+entity_id
			$("a").removeClass('active')
			$(s).addClass('active')
			$("#tabcontent").html(data)
			var lastSubCommand = getCookie('lastSubCommand')
			var selected_index
			if (lastSubCommand == 'get_admin_table_func')
			{
				var lastSubCommandParam = getCookie('lastSubCommandParam')
				var param = lastSubCommandParam.split(',')
				entity_id = param[0]
				entity_value_id = param[1]
				selected_index = param[2]
			}
			get_admin_table_func(entity_id, entity_value_id, selected_index)
		})
	}
	setCookie('lastUrl', location.href)
	setCookie('lastCommand', 'get_admin_func')
	setCookie('lastCommandParam', [section, entity_id, entity_value_id])
}
function change_bound_select(this_name, child_name, entity_id){
	if (!is_ready)
		return
	this_select = '#property-' + this_name
	child_select = '#property-' + child_name
	var this_entity = $(this_select)
	var child_entity = $(child_select)
	if (this_entity.length != 0 && child_entity.length != 0)
	{
		var entity_value_id = this_entity[0][this_entity[0].selectedIndex].value;
		if(entity_value_id == '')
			entity_value_id = 0

		$.get("/entity/request_entity_select/" + entity_value_id + "/" + entity_id + "/", function(data) {
			child_entity.html(data)

		var str = child_entity[0].text
		if (child_entity[0].selectedIndex != -1)
			str = child_entity[0][child_entity[0].selectedIndex].text;
		else
			str = ''
		child_entity.prevAll('.outer:first').html("<span>" + str + "</span>");
			try
			{
		path =	child_entity[0].attributes.onchange.value
		part = path.split('\'')
		change_bound_select(part[part.length-6], part[part.length-4], part[part.length-2])
			}
			catch(e)
			{}
		tb_hover();
	})
	}


}

$(document).ready(function() {
//	activate_fields()
	draw_menu()
	$("#out-parent.outer").before("<div id='parent'>#158888</div>");
	$("#field-parent").change(
			function () {
				var str = $(this).val();
				str1 = str.replace('#', "");
				$(this).prevAll('#parent').html("<span><a href='ticket/" + str1 + "'>" + str + "</a></span>");
			}).change();
	$("#create_entity").dialog({modal:true, autoOpen: false, width:1000,open:
			function(event, ui) {
			}});
	var lastCommand = getCookie('lastCommand')
	var lastCommandParam = getCookie('lastCommandParam')
	var lastUrl = getCookie('lastUrl')
	var curUrl = location.href
	if (lastCommand != undefined && lastCommand != "" && lastUrl == curUrl)
		window[lastCommand](lastCommandParam)
//	$("#entity_list_{{ entity.entity_id }}").dataTable()

})

